<template>
  <div class="user-management">
    <el-button color="#19af7d" @click="addUser" style="margin-bottom: 20px">新增用户</el-button>

    <el-table :data="userList" border style="width: 100%">
      <el-table-column prop="id" label="编号" width="80" align="center" />
      <el-table-column prop="account" label="账户" align="center" />
      <el-table-column prop="name" label="姓名" align="center" />
      <el-table-column prop="phone" label="电话" align="center" />
      <el-table-column prop="role" label="角色" align="center" />
      <el-table-column label="操作" width="180" align="center">
        <template #default="scope">
          <el-button size="small" @click="editUser(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="deleteUser(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <Form
      v-model="dialogVisible"
      :isEdit="isEdit"
      :userFormData="userForm"
      @save="handleSave"
    />
  </div>
</template>

<script setup>
import { ref, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import Form from "./form.vue";

// 所有用户数据
const allUsers = ref([
  { id: 1, account: "admin", name: "管理员", phone: "13790998675", role: "管理员" },
  { id: 2, account: "user1", name: "普通用户", phone: "13790998674", role: "普通用户" },
]);

const dialogVisible = ref(false);
const isEdit = ref(false);
// 用户表单数据
const userForm = ref({ id: null, account: "", name: "", phone: "", role: "" });

// 用户列表
const userList = computed(() => [...allUsers.value]);

const addUser = () => {
  isEdit.value = false;
  userForm.value = { id: null, account: "", name: "", phone: "", role: "" };
  dialogVisible.value = true;
};

const editUser = (row) => {
  isEdit.value = true;
  userForm.value = { ...row };
  dialogVisible.value = true;
};

const generateId = () => {
  return Math.max(...allUsers.value.map((item) => item.id), 0) + 1;
};

const handleSave = (data) => {
  dialogVisible.value = false;
  if (isEdit.value) {
    const index = allUsers.value.findIndex((item) => item.id === data.id);
    if (index !== -1) {
      allUsers.value = [
        ...allUsers.value.slice(0, index),
        data,
        ...allUsers.value.slice(index + 1),
      ];
    }
  } else {
    const newUser = { ...data, id: generateId() };
    allUsers.value = [...allUsers.value, newUser];
  }
  ElMessage.success(isEdit.value ? "编辑用户成功" : "新增用户成功");
};

const deleteUser = (id) => {
  ElMessageBox.confirm("确定要删除该用户吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      allUsers.value = allUsers.value.filter((item) => item.id !== id);
      ElMessage.success("删除用户成功");
    })
    .catch(() => {});
};
</script>

<style scoped lang="scss">
</style>
